/**
 * API接口封装
 * 处理与后端的所有HTTP请求
 */
/*
// 在 api.js 文件最开头添加
if (window.API) {
    console.warn('API already defined, skipping reinitialization');
    // 如果API已经存在，直接返回
    if (typeof module !== 'undefined' && module.exports) {
        module.exports = window.API;
    }
    return;
}*/

// API配置
const API_CONFIG = {
    baseURL: 'http://localhost:5000', // 修改为正确的后端服务地址
    timeout: 10000, // 请求超时时间
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
    }
};

// API类
class API {
    constructor() {
        this.baseURL = API_CONFIG.baseURL;
        this.timeout = API_CONFIG.timeout;
        this.token = localStorage.getItem('token') || '';
    }

    /**
     * 设置认证token
     * @param {string} token - JWT token
     */
    setToken(token) {
        this.token = token;
        localStorage.setItem('token', token);
        console.log('Token saved:', token); // 打印保存的 token

    }

    /**
     * 清除认证token
     */
    clearToken() {
        this.token = '';
        localStorage.removeItem('token');
    }

    /**
     * 发送HTTP请求
     * @param {string} url - 请求URL
     * @param {Object} options - 请求选项
     */
    async request(url, options = {}) {
        //let finalUrl = url.startsWith('http') ? url : `${this.baseURL}${url}`;

        const {
            method = 'GET',
            data = null,
            headers = {},
            timeout = this.timeout
        } = options;

        // 构建完整URL
        const fullUrl = url.startsWith('http') ? url : `${this.baseURL}${url}`;

        // 构建请求头
        const requestHeaders = {
            ...API_CONFIG.headers,
            ...headers
        };

        // 构建请求体
        let body = null;
        if (data) {
            if (method === 'GET') {
                // GET请求将数据作为查询参数
                const params = new URLSearchParams(data);
                const separator = fullUrl.includes('?') ? '&' : '?';

                url = `${fullUrl}${separator}${params.toString()}`;
                //finalUrl = `${finalUrl}${separator}${params.toString()}`;

            } else {
                // POST请求将数据作为表单数据
                if (data instanceof FormData) {
                    body = data;
                    delete requestHeaders['Content-Type']; // 让浏览器自动设置
                } else {
                    const formData = new URLSearchParams();
                    Object.keys(data).forEach(key => {
                        if (data[key] !== null && data[key] !== undefined) {
                            formData.append(key, data[key]);
                        }
                    });
                    body = formData;
                }
            }
        }

        // 添加token到请求数据中（后端要求token在form data中）
        if (this.token && method !== 'GET') {
            if (body instanceof FormData) {
                body.append('token', this.token);
            } else if (body instanceof URLSearchParams) {
                body.append('token', this.token);
            } else {
                body = body || new URLSearchParams();
                body.append('token', this.token);
            }
        }

        try {
            // 创建AbortController用于超时控制
            const controller = new AbortController();
            const timeoutId = setTimeout(() => controller.abort(), timeout);

            const response = await fetch(fullUrl /* finalUrl */, {
                method,
                headers: requestHeaders,
                body,
                signal: controller.signal
            });

            clearTimeout(timeoutId);

            // 检查响应状态
            if (!response.ok) {
                throw new Error(`HTTP ${response.status}: ${response.statusText}`);
            }

            // 解析响应数据
            const contentType = response.headers.get('content-type');
            let result;

            if (contentType && contentType.includes('application/json')) {
                result = await response.json();
            } else {
                result = await response.text();
            }

            return result;

        } catch (error) {
            console.error('API请求失败:', error);

            if (error.name === 'AbortError') {
                throw new Error('请求超时，请检查网络连接');
            }

            if (error.message.includes('Failed to fetch')) {
                throw new Error('网络连接失败，请检查网络设置');
            }

            throw error;
        }
    }

    /**
     * GET请求
     * @param {string} url - 请求URL
     * @param {Object} params - 查询参数
     * @param {Object} options - 请求选项
     */
    async get(url, params = {}, options = {}) {
        return this.request(url, {
            method: 'GET',
            data: params,
            ...options
        });
    }

    /**
     * POST请求
     * @param {string} url - 请求URL
     * @param {Object} data - 请求数据
     * @param {Object} options - 请求选项
     */
    async post(url, data = {}, options = {}) {
        return this.request(url, {
            method: 'POST',
            data,
            ...options
        });
    }

    /**
     * PUT请求
     * @param {string} url - 请求URL
     * @param {Object} data - 请求数据
     * @param {Object} options - 请求选项
     */
    async put(url, data = {}, options = {}) {
        return this.request(url, {
            method: 'PUT',
            data,
            ...options
        });
    }

    /**
     * DELETE请求
     * @param {string} url - 请求URL
     * @param {Object} data - 请求数据
     * @param {Object} options - 请求选项
     */
    async delete(url, data = {}, options = {}) {
        return this.request(url, {
            method: 'DELETE',
            data,
            ...options
        });
    }
}

// 创建API实例
const api = new API();

// 用户相关API
const UserAPI = {
    /**
     * 用户登录
     * @param {string} username - 用户名
     * @param {string} password - 密码
     */
    async login(username, password) {
        try {
            const result = await api.post('/user/login', { username, password });

            if (result.status === 'success') {
                api.setToken(result.token);
                return { success: true, token: result.token };
            } else {
                return { success: false, message: result.status };
            }
        } catch (error) {
            return { success: false, message: error.message };
        }
    },

    /**
     * 用户注册
     * @param {string} username - 用户名
     * @param {string} password - 密码
     */
    async register(username, password) {
        try {
            const result = await api.post('/user/new', { username, password });

            if (result.status === 'success') {
                return { success: true };
            } else {
                return { success: false, message: result.status };
            }
        } catch (error) {
            return { success: false, message: error.message };
        }
    }
};

// 违约管理API
const BreachAPI = {
    /**
     * 获取客户列表
     */
    async getCustomers() {
        try {
            const result = await api.post('/weiyue/custom');
            return { success: true, data: result };
        } catch (error) {
            return { success: false, message: error.message };
        }
    },

    /**
     * 添加新客户
     * @param {Object} customerData - 客户数据
     */
    async addCustomer(customerData) {
        try {
            const result = await api.post('/weiyue/custom/add', customerData);

            if (result.status === 'success') {
                return { success: true };
            } else {
                return { success: false, message: result.status };
            }
        } catch (error) {
            return { success: false, message: error.message };
        }
    },

    /**
     * 获取违约原因列表
     * @param {number} enable - 是否启用 (1: 启用, 0: 禁用, null: 全部)
     */
    async getBreachReasons(enable = null) {
        try {
            const data = enable !== null ? { enable } : {};
            const result = await api.post('/weiyue/reason', data);
            return { success: true, data: result };
        } catch (error) {
            return { success: false, message: error.message };
        }
    },

    /**
     * 修改违约原因状态
     * @param {string} reasonid - 原因ID
     * @param {number} enable - 是否启用 (1: 启用, 0: 禁用)
     */
    async changeBreachReasonStatus(reasonid, enable) {
        try {
            const result = await api.post('/weiyue/change_reason', { reasonid, enable });

            if (result.status === 'success') {
                return { success: true };
            } else {
                return { success: false, message: result.status };
            }
        } catch (error) {
            return { success: false, message: error.message };
        }
    },

    /**
     * 提交违约申请
     * @param {Object} applicationData - 申请数据
     */
    async submitBreachApplication(applicationData) {
        try {
            const result = await api.post('/weiyue/apply', applicationData);

            if (result.status === 'success') {
                return { success: true };
            } else {
                return { success: false, message: result.status };
            }
        } catch (error) {
            return { success: false, message: error.message };
        }
    },

    /**
     * 审核违约申请
     * @param {string} id - 申请ID
     * @param {string} passed - 审核结果 ('审核通过' 或 '审核未通过')
     */
    async verifyBreachApplication(id, passed) {
        try {
            const result = await api.post('/weiyue/verify', { id, passed });

            if (result.status === 'success') {
                return { success: true };
            } else {
                return { success: false, message: result.status };
            }
        } catch (error) {
            return { success: false, message: error.message };
        }
    },

    /**
     * 获取违约记录
     * @param {string} status - 审核状态筛选
     */
    async getBreachRecords(status = null) {
        try {
            const data = status ? { passed: status } : {};
            const result = await api.post('/weiyue/records', data);
            return { success: true, data: result };
        } catch (error) {
            return { success: false, message: error.message };
        }
    },

    // 在BreachAPI对象中添加
    /**
     * 获取行业统计数据
    * @param {number} year - 年份
     */
    async getIndustryStatistics(year = 2024) {
        try {
            const result = await api.post('/weiyue/statistics/industry', { year });
            if (result.success) {
                return { success: true, data: result.data };
            } else {
                return { success: false, message: result.message };
            }
        } catch (error) {
            return { success: false, message: error.message };
        }
    },

    /**
     * 获取区域统计数据
     * @param {number} year - 年份
     */
    async getRegionStatistics(year = 2024) {
        try {
            const result = await api.post('/weiyue/statistics/region', { year });
            if (result.success) {
                return { success: true, data: result.data };
            } else {
                return { success: false, message: result.message };
            }
        } catch (error) {
            return { success: false, message: error.message };
        }
    }
};

// 恢复管理API
const RecoveryAPI = {
    /**
     * 获取恢复原因列表
     */
    async getRecoveryReasons(enable = null) {
        try {
            const result = await api.post('/remake/reason');
            // 后端暂不支持 enable 过滤，这里前端兼容性过滤
            const list = Array.isArray(result) ? result : [];
            const filtered = (enable === null) ? list : list.filter(r => String(r.是否启用 ?? '1') === String(enable));
            return { success: true, data: filtered };
        } catch (error) {
            return { success: false, message: error.message };
        }
    },

    /**
     * 修改恢复原因状态（参考违约原因管理接口风格）
     * @param {string|number} reasonid - 原因ID
     * @param {number} enable - 是否启用 (1: 启用, 0: 禁用)
     */
    async changeRecoveryReasonStatus(reasonid, enable) {
        try {
            const result = await api.post('/remake/change_reason', { reasonid, enable });
            if (result.status === 'success') {
                return { success: true };
            } else {
                return { success: false, message: result.status };
            }
        } catch (error) {
            return { success: false, message: error.message };
        }
    },

    /**
     * 提交恢复申请
     * @param {Object} applicationData - 申请数据
     */
    async submitRecoveryApplication(applicationData) {
        try {
            const result = await api.post('/remake/apply', applicationData);

            if (result.status === 'success') {
                return { success: true };
            } else {
                return { success: false, message: result.status };
            }
        } catch (error) {
            return { success: false, message: error.message };
        }
    },

    /**
     * 审核恢复申请
     * @param {string} id - 申请ID
     * @param {string} passed - 审核结果 ('审核通过' 或 '审核未通过')
     */
    async verifyRecoveryApplication(id, passed) {
        try {
            const result = await api.post('/remake/verify', { id, passed });

            if (result.status === 'success') {
                return { success: true };
            } else {
                return { success: false, message: result.status };
            }
        } catch (error) {
            return { success: false, message: error.message };
        }
    },

    /**
     * 获取恢复记录
     * @param {string} status - 审核状态筛选
     */
    async getRecoveryRecords(status = null) {
        try {
            const data = status ? { passed: status } : {};
            const result = await api.post('/remake/records', data);
            return { success: true, data: result };
        } catch (error) {
            return { success: false, message: error.message };
        }
    }
};

// 导出API对象
window.API = {
    api,
    UserAPI,
    BreachAPI,
    RecoveryAPI
};
